package com.ck.util;

import com.ck.entity.HtmlEntity;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        try {
            Document document = Jsoup.parse(new File("D:/Download/bookmarks_qq_2019_12_18.html"), "utf-8");
            Element element = document.body().children().select("dl").first();
            parseElement(element);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void parseElement(Element element){
        Elements elements = element.children().select("dt");
        List<HtmlEntity> list = new ArrayList();
        Set<String> set = new HashSet<>();
        for(Element ele:elements){
            parseNode(ele,list,set,"1");
        }
        System.out.println(set);
        System.out.println(list.size());
        System.out.println(list);
    }

    private static void parseNode(Element node,List<HtmlEntity> list,Set<String> set,String pid){
        Elements eq0 = node.children().eq(0);
        if(!"true".equals(eq0.attr("PERSONAL_TOOLBAR_FOLDER"))){
            String name = eq0.html();
            HtmlEntity htmlEntity;

            switch (eq0.get(0).tagName()){
                case "h3":
                    String folderId = UUID.randomUUID().toString().replace("-", "");
                    htmlEntity = new HtmlEntity(folderId,pid,name,0,"","");
                    if(!set.contains(name)){
                        list.add(htmlEntity);
                    }
                    set.add(name);
                    Element dl = node.children().select("dl").first();
                    Elements dts = dl.children();
                    for(Element ele:dts){
                        if(ele.tagName() == "dt"){
                            parseNode(ele,list,set,folderId);
                        }
                    }
                    break;
                case "a":

                    String siteId = UUID.randomUUID().toString().replace("-", "");
                    String href = eq0.attr("href");
                    String icon = eq0.attr("icon");
                    htmlEntity = new HtmlEntity(siteId,pid,name,1,href,icon);
                    if(!set.contains(href)){
                        list.add(htmlEntity);
                    }
                    set.add(href);
                    break;
            }

        }
    }

}
